import { Component, ViewChild, OnInit } from '@angular/core';
import { ServerDataSource } from 'ng2-smart-table';
// api
import { BasicService } from '../../../@core/data/basic.service';
// import { Observable } from 'rxjs/Rx';
import { Http } from '@angular/http';
// 消息提醒
import { ToasterConfig } from 'angular2-toaster';
import { NotificationsService } from '../../../@core/utils/notifications.service';
// confirm
import { SwalComponent } from '@toverux/ngx-sweetalert2';
// 新增修改的modal
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { PaperModalComponent } from './modal/paper.modal.component';


const api = 'papers';
@Component({
  selector: 'ngx-smart-table-paper',
  templateUrl: './paper.component.html',
  styles: [`
    nb-card {
      transform: translate3d(0, 0, 0);
    }
  `],

})
export class PaperComponent implements OnInit {
  @ViewChild('deleteSwal') private deleteSwal: SwalComponent;

  settings = {
    // selectMode: 'multi', //多选，全选操作未实现
    actions: {
      columnTitle: '操作',
      position: 'right',
    },
    noDataMessage: '暂无数据',
    mode: 'external',
    pager: {
      perPage: 10,
    },
    add: {
      addButtonContent: '<i class="nb-plus"></i>',
      createButtonContent: '<i class="nb-checkmark"></i>',
      cancelButtonContent: '<i class="nb-close"></i>',
      confirmCreate: true,
    },
    edit: {
      editButtonContent: '<i class="nb-edit"></i>',
      saveButtonContent: '<i class="nb-checkmark"></i>',
      cancelButtonContent: '<i class="nb-close"></i>',
      confirmSave: true,
    },
    delete: {
      deleteButtonContent: '<i class="nb-trash"></i>',
      confirmDelete: true,
    },
    columns: {
      // id: {
      //   title: 'ID',
      //   type: 'number',
      //   sort: 'enable',//表内排序
      //   sortDirection: 'desc'
      // },
      courseName: {
        title: '课程',
        // filter: false,
        type: 'string',
      },
      qbankName: {
        title: '题库',
        // filter: false,
        type: 'string',
      },
      title: {
        title: '试卷名称',
        type: 'html',
        // filter: false,
      },
      statusName: {
        title: '状态',
        // editable: false,
        // addable: false,
        // filter: false,
        type: 'string',
      },
      // age: {
      //   title: '年龄',
      //   type: 'number',
      // },
    },
  };
  source: ServerDataSource;
  config: ToasterConfig;
  constructor(private service: BasicService, private http: Http,
    private notificationsService: NotificationsService, private modalService: NgbModal) {
    this.source = new ServerDataSource(http,
      {
        endPoint: this.service.api + api,
        totalKey: this.service.totalKey,
        dataKey: this.service.dataKey,
        sortFieldKey: this.service.sortFieldKey,
        sortDirKey: this.service.sortDirKey,
        pagerPageKey: this.service.pagerPageKey,
        pagerLimitKey: this.service.pagerLimitKey,
        filterFieldKey: this.service.filterFieldKey,
      });
    this.config = this.notificationsService.getConfig();
  }

  ngOnInit() {

  }

  /**
   * 新增操作
   * @param event
   */
  onCreate(event) {
    const activeModal = this.modalService.open(PaperModalComponent, { size: 'lg', container: 'nb-layout' });
    activeModal.componentInstance.modalHeader = '新增试卷';
    activeModal.componentInstance.source = this.source;
    activeModal.componentInstance.paper = {
      content: {},
    };
  }

  /**
   * 更新
   * @param event
   */
  onEdit(event) {
    const activeModal = this.modalService.open(PaperModalComponent, { size: 'lg', container: 'nb-layout' });
    activeModal.componentInstance.modalHeader = '编辑试卷';
    activeModal.componentInstance.source = this.source;
    activeModal.componentInstance.isEdit = true;
    if (!event.data.content) {
      event.data.content = {};
    } else {
      if (typeof (event.data.content) === 'string') {
        event.data.content = JSON.parse(event.data.content);
      }
    }
    activeModal.componentInstance.paperId = event.data.id;
    activeModal.componentInstance.paper = event.data;
    const qtype = event.data.qtype;
    if (qtype === 'single_choice' || qtype === 'multiple_choice') {
      activeModal.componentInstance.choiceHidden = false;
    } else {
      activeModal.componentInstance.choiceHidden = true;
    }
  }

  /**
   * 删除
   * @param event
   */
  onDelete(event): void {
    this.deleteSwal.show().then(option => {
      if (option.value) {
        this.delete(event);
      }
    }).catch(err => {
      console.error(err);
      event.confirm.reject();
    });
  }

  delete(event) {
    const id = event.data.id;
    const url = api + '/' + id;
    this.service.delete(url).subscribe(
      data => {
        this.notificationsService.showToast('success', '操作', '<b>删除 <em>成功！</em></b>');
        // refresh the list
        this.source.refresh();
      },
      err => {
        this.notificationsService.showToast('error', '操作', '<b>删除 <em>失败！</em></b>');
        console.error('Error deleting!');
        event.confirm.reject();
      },
    );
  }

}
